package main

import (
	// "flag"
	"bufio"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math/rand"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

var FileName string

const (
	card_path     string = "./card/"
	card_pathName string = "card"
)

func main() {
	r := bufio.NewReader(os.Stdin)
	for {
		fmt.Println("数据正确格式(可直接从控制台中复制)\n")
		fmt.Println("将\"action=\"后 包括 { } 内全部复制进输入然后Enter\n")
		fmt.Print("输入数据(默认生成在可执行文件路径下 指令clear可删除所有做牌文件):\n")
		rawLine, _, _ := r.ReadLine()

		line := string(rawLine)

		tokens := strings.Split(line, " ")
		fmt.Println("已输入数据:\n", tokens[0])
		cur := tokens[0]
		switch cur {
		case "clear":
			clearAllFiles()
			break
		case "":
			fmt.Println("数据不能为空!")
			break
		default:
			var data map[string]interface{}
			json.Unmarshal([]byte(cur), &data)
			fmt.Println("解析格式化: \n", data)
			fmt.Println("\n")
			writerHandler(data)
			break
		}

	}
}

const template string = `#{
    <<"shoupai">> =>{{shoupai}},
    <<"zhuangpai">> =>{{zhuangpai}},
    <<"baopai">> =>{{baopai}},
    <<"dui">> =>{{dui}}
}.`

func writerHandler(_data map[string]interface{}) {
	tmp := template
	var data map[string]interface{}
	for _, v := range _data {
		if val, ok := v.(map[string]interface{}); ok {
			data = val
		}
	}

	parseHandler(data, "baopai", &tmp)
	parseHandler(data, "zhuangpai", &tmp)
	parseHandler(data, "shoupai", &tmp)
	parseHandler(data, "dui", &tmp)

	gid, _ := json.Marshal(data["gid"])
	uid, _ := json.Marshal(data["uid"])
	rid, _ := json.Marshal(data["rid"])
	if len(gid) > 0 && len(uid) > 0 && len(uid) > 0 {
		FileName = string(gid) + "_" + string(uid) + "_" + string(rid)
		FileName = strings.Replace(FileName, "\"", "", -1)
	}

	writeFile(tmp)
}

func parseHandler(data map[string]interface{}, key string, tmp *string) string {
	if data[key] != nil {
		item := data[key]
		itemStr, _ := json.Marshal(item)
		str := strings.Replace(string(itemStr), "\"", "", -1)
		*tmp = strings.Replace(*tmp, "{{"+key+"}}", str, 1)
	} else {
		*tmp = strings.Replace(*tmp, "{{"+key+"}}", "[]", 1)
	}
	return *tmp
}

func writeFile(content string) {
	fileName := getFileName()
	b := []byte(content)
	err := ioutil.WriteFile(fileName, b, os.ModeAppend)
	if err != nil {
		fmt.Println("文件写入错误: ", err)
	}

}

func getFileName() string {
	var fileName string
	if FileName != "" {
		fileName = FileName + ".txt"
	} else {
		fileId := strconv.Itoa(rand.Intn(99999))
		fileName = "txt_" + fileId + ".txt"
	}
	return card_path + fileName
}

/*判断路径是否存在*/

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)

	if err == nil {
		return true, nil
	}

	if os.IsNotExist(err) {
		return false, nil
	}

	return false, err
}

/**清理文件夹*/
func clearAllFiles() {
	destorytemp(card_path)
}

func destorytemp(path string) {
	filepath.Walk(path, func(_path string, fi os.FileInfo, err error) error {
		if nil == fi {
			return err
		}
		if !fi.IsDir() {
			return nil
		}

		name := fi.Name()
		fmt.Println("name :", name)
		if fi.IsDir() && strings.Contains(name, card_pathName) {
			flist, err := ioutil.ReadDir(fi.Name())
			if err != nil {
				fmt.Println("Open dir error ", err)
				return err
			}

			for _, f := range flist {
				if !f.IsDir() {
					r := _path + "/" + f.Name()
					err := os.Remove(r)
					if err != nil {
						fmt.Println("Romve file error ", err)
						return err
					}
					fmt.Println("Romve success ", r)
				}
			}
		}

		return nil
	})
}
